const net = require('net');
const Parer = require('./Parser');
const fs = require('fs')
const path = require('path')
var boundary;
const server = net.createServer((socket) => {

  socket.on('data', (data) => {

    let parser = new Parer();
    let {method,url,headers,body}= parser.parse(data);
    // console.log('method', method); 
    // console.log('url', url);
    // console.log('headers', headers);
    // console.log('body', body);
    // console.log(url)
    if (url === '/favicon.ico') {
      socket.end(`HTTP/1.1 404 Not Found`);
    }
    if (url === '/') {
      let rows = [];
      rows.push(`HTTP/1.1 200 OK`);
      rows.push(`Context-type: text/plain;charset=utf-8;`);
      rows.push(`Date: ${new Date().toGMTString()}`);
      rows.push(`Connection: keep-alive`);
      rows.push(`Transfer-Encoding: chunked`);
      let responseBody = `${fs.readFileSync('./static/upload.html','utf8')}`;
      rows.push(`\r\n${Buffer.byteLength(responseBody).toString(16)}\r\n${responseBody}\r\n0\r\n\r\n`);

      let response = rows.join('\r\n');
      socket.end(response);
      return;
    }
    if (url === '/upload'){
       boundary = headers['Content-Type'].match(/boundary=([^;]+)/i)[1];
       return ;
    }
    console.log(11)
  
    // var boundary = headers['Content-Type'].match(/boundary=([^;]+)/i)[1];
    let parts = body.split('--' + boundary).slice(1, -1);
    parts = parts.map(item => item.slice(2, -2));
    let fields = {};
    let files = {};
    for (let i = 0; i < parts.length; i++) {
      let part = parts[i];
      let rows = part.split('\r\n');
      if (rows.length == 3) {
        let [key, , value] = rows;
        let [, name] = key.toString().match(/name="([^"]+?)"/);
        fields[name] = value.toString();
      } else if (rows.length == 4) {
        let [key, type, , value] = rows;
        let [, name, filename] = key.toString().match(/name="([^"]+?)"; filename="([^"]+?)"/);
        let filePath = path.join(__dirname, 'static', filename);
        fs.writeFileSync(filePath, value);
        files[name] = {
          name,
          filename,
          path: filePath
        };
      }
    }
    // console.log(fields);
    // console.log(files);
    let rows = [];
    rows.push(`HTTP/1.1 200 OK`);
    rows.push(`Context-type: text-plain`);
    rows.push(`Date: ${new Date().toGMTString()}`);
    rows.push(`Connection: keep-alive`);
    rows.push(`Transfer-Encoding: chunked`);
    //  console.log(body)
    let responseBody = JSON.stringify({
      ...fields,
      ...files
    });
    rows.push(`\r\n${Buffer.byteLength(responseBody).toString(16)}\r\n${responseBody}\r\n0\r\n\r\n`);

    let response = rows.join('\r\n');
  
     socket.end(response);
     socket.end();



  });

  socket.on('end', (data) => {
    //  console.error('end', data);
  });
})

server.on('error', (err) => {
  console.error(err);
});

server.listen(8083, () => {
  console.log('服务器已经启动', server.address());
});